using System;

namespace Tycho.Parser.Peg {
    public class FloatingPointProduction : Production {
        private readonly IProduction IntegerTerminal;

        public FloatingPointProduction () {
            IntegerTerminal = IntegerProduction.CreateTerminal ();
            Name = "real";
            ErrorInformation = new ProductionErrorInformation ("floating-point");
        }

        public static Terminal CreateTerminal () {
            return new Terminal (new FloatingPointProduction ());
        }

        protected override ParseResult ReallyParse (char[] source, int startIndex, ParseContext context, string sourceString, ParseEnvironment parseEnvironment) {
            ParseResult result = IntegerTerminal.Parse (source, startIndex, context, sourceString, parseEnvironment);

            if (result != null) {
                int index = result.Index;

                if (index < source.Length && source[index] == '.') {
                    index++;

                    result = IntegerTerminal.Parse (source, index, context, sourceString, parseEnvironment);

                    if (result != null) {
                        double value;
                        if (double.TryParse (new string (source, startIndex, result.Index - startIndex), out value)) {
                            SourceInformation sinfo = parseEnvironment.SourceFileInformation.CreateSourceInformation (startIndex, result.Index - startIndex);
                            var term = new FloatingPointTerm (value, sinfo);
                            return new ParseResult (result.Index, term, context);
                        }
                    }
                }
            }

            return null;
        }
    }
}